using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Test.Db;
using Test.Models;
namespace Test.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly TestDb _db;
        private readonly DbSet<T> _table;

        public EfRepository()
        {
            _db=new TestDb();
            _table=_db.Set<T>();
        }
        public IQueryable<T> Table
        {
            get
            {
                return _table as IQueryable<T>; 
            }
        }

        public T GetById(int id)
        {
            var entity=_table.Where(x=>x.ID==id).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
            if(entity==null){
                throw new Exception();
            }
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.UpdatedTime=DateTime.Now;
            entity.CreatedTime=DateTime.Now;

            _table.Add(entity);
            _db.SaveChanges();
        }
        public void Update(T entity)
        {
            if(entity==null){
                throw new Exception();
            }
            if(entity.ID==0){
                throw new Exception();
            }
            entity.UpdatedTime=DateTime.Now;
            
            _table.Update(entity);
            _db.SaveChanges();
        }
        public void Delete(int id)
        {
            var entity=GetById(id);
            if(entity==null){
                throw new Exception();
            }
            entity.IsDeleted=true;
            entity.UpdatedTime=DateTime.Now;
            
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}